// 引入MD5加密
import md5 from './md5'

//验证身份证有效性
function checkIdLience(cardNum) {
  let idcard = cardNum.toUpperCase() // 对身份证号码做处理,处理英文大小写问题
  let ereg
  let Y, JYM
  let S, M

  /*基本校验*/
  //if (String.isNullOrEmpty(idcard)) return false;
  let idcard_array = new Array()
  idcard_array = idcard.split("")

  /*身份号码位数及格式检验*/
  switch (idcard.length) {
    case 15:
      if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/ //测试出生日期的合法性
      } else {
        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/ //测试出生日期的合法性
      }
      if (ereg.test(idcard)) {
        return true
      } else {
        return false
      }
      break
    case 18:
      //18位身份号码检测
      //出生日期的合法性检查
      //闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))
      //平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))
      if (parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0)) {
        ereg = /^[1-9][0-9]{5}(19|2[0-9])[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9XxAa]$/ //闰年出生日期的合法性正则表达式
      } else {
        ereg = /^[1-9][0-9]{5}(19|2[0-9])[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9XxAa]$/ //平年出生日期的合法性正则表达式
      }
      if (ereg.test(idcard)) { //测试出生日期的合法性
        //计算校验位
        S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 +
          (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 +
          (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 +
          (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 +
          (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 +
          (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 +
          (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 +
          parseInt(idcard_array[7]) * 1 +
          parseInt(idcard_array[8]) * 6 +
          parseInt(idcard_array[9]) * 3
        Y = S % 11
        M = "F"
        JYM = "10X98765432"
        M = JYM.substr(Y, 1)
        /*判断校验位*/
        if (M == idcard_array[17]) { /*检测ID的校验位false;*/
          return true
        } else if (idcard_array[17] == 'A') { //A结尾不校验规则
          return true
          /*检测ID的校验位false;*/
        } else {
          return false
        }
      } else {
        return false
      }
      break
    default:
      return false
  }
}

//获得随机字符串
function createNonce(length = 32, current) {
  current = current ? current : ''
  return length ? createNonce(--length, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current
}

//生成签名
function createSign(params, secretkey = '') {
  if (!!params) {
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        let value = params[key]
        if (value == null || value === '') {
          delete params[key]
        }
      }
    }
  } else {
    params = {}
  }

  params.nonce = createNonce(32)

  return md5.created(sortSign(params) + "key=" + secretkey)
}

//签名排序
function sortSign(params) {
  let keys = Object.keys(params).sort()
  let param_str = ''
  for (let i = 0; i < keys.length; i++) {
    param_str += keys[i] + "=" + params[keys[i]] + "&"
  }
  return param_str
}

function isMobile(value) {
  let length = value.length
  let mobile = /^(13[0-9]|15[012356789]|16[6]|17[0135678]|18[0-9]|19[89])[0-9]{8}$/
  return mobile.test(value)
}

function checkPwd(s) {
  if (!/^\d{6}$/.test(s)) return false // 不是6位数字
  if (/^(\d)\1+$/.test(s)) return false  // 全一样

  var str = s.replace(/\d/g, function ($0, pos) {
    return parseInt($0) - pos
  })
  if (/^(\d)\1+$/.test(str)) return false  // 顺增

  str = s.replace(/\d/g, function ($0, pos) {
    return parseInt($0) + pos
  })
  if (/^(\d)\1+$/.test(str)) return false  // 顺减
  return true

}

function Deserialize(utldata) {
  let paramsString = utldata.replace("?", "")
  let paramsTempObj = paramsString.split("&")
  let paramsObj = {}
  for (let i = 0; i < paramsTempObj.length; i++) {
    paramsObj[paramsTempObj[i].split("=")[0]] = paramsTempObj[i].split("=")[1]
  }
  return paramsObj
}

function detect(ua, platform) {
  var os = this.os = {}, browser = this.browser = {},
    webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/),
    android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
    osx = !!ua.match(/\(Macintosh\; Intel /),
    ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
    ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
    iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
    webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
    win = /Win\d{2}|Windows/.test(platform),
    wp = ua.match(/Windows Phone ([\d.]+)/),
    touchpad = webos && ua.match(/TouchPad/),
    kindle = ua.match(/Kindle\/([\d.]+)/),
    silk = ua.match(/Silk\/([\d._]+)/),
    blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/),
    bb10 = ua.match(/(BB10).*Version\/([\d.]+)/),
    rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/),
    playbook = ua.match(/PlayBook/),
    chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
    firefox = ua.match(/Firefox\/([\d.]+)/),
    firefoxos = ua.match(/\((?:Mobile|Tablet); rv:([\d.]+)\).*Firefox\/[\d.]+/),
    ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),
    webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
    safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/),
    weChat = (ua.toLowerCase().match(/MicroMessenger/i) == 'micromessenger')
    
  if (browser.webkit = !!webkit) browser.version = webkit[1] 
  if(weChat) os.weChat = true
  if (android) os.android = true, os.version = android[2]
  if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.')
  if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.')
  if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null
  if (wp) os.wp = true, os.version = wp[1]
  if (webos) os.webos = true, os.version = webos[2]
  if (touchpad) os.touchpad = true
  if (blackberry) os.blackberry = true, os.version = blackberry[2]
  if (bb10) os.bb10 = true, os.version = bb10[2]
  if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]
  if (playbook) browser.playbook = true
  if (kindle) os.kindle = true, os.version = kindle[1]
  if (silk) browser.silk = true, browser.version = silk[1]
  if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true
  if (chrome) browser.chrome = true, browser.version = chrome[1]
  if (firefox) browser.firefox = true, browser.version = firefox[1]
  if (firefoxos) os.firefoxos = true, os.version = firefoxos[1]
  if (ie) browser.ie = true, browser.version = ie[1]
  if (safari && (osx || os.ios || win)) {
    browser.safari = true
    if (!os.ios) browser.version = safari[1]
  }
  if (webview) browser.webview = true

  os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
    (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)))
  os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 ||
    (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
    (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))))
  return os
}

function filter2Num(value) {
  return value.match(/\d/ig) ? value.match(/\d/ig).join('') : ''
}
//保留小数点后2位，没有就补.00
function toDecimal2(x) {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x*100)/100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}
export default {
  createSign: createSign,
  checkIdLience: checkIdLience,
  isMobile: isMobile,
  checkPwd: checkPwd,
  detect: detect,
  filter2Num: filter2Num,
  toDecimal2:toDecimal2,
  Deserialize: Deserialize
}
